package game.socket;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import java.nio.ByteBuffer;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 服务端通知客户端的工具类
 * @author wizardc
 */
public class NotifyUtil
{
    private static Logger logger = LogManager.getLogger("GameServer");

    private static final ConcurrentHashMap<Integer, RemoteClientSocket> _clientMap = ClientSocketManager.getInstance().getClientMap();

    /**
     * 发送协议包给一个用户
     * @param uid 要接收该协议包的用户 ID
     * @param byteBuffer 要发送的协议包
     */
    public static void notify(int uid, ByteBuffer byteBuffer)
    {
        RemoteClientSocket client = _clientMap.get(uid);
        if(client != null)
        {
            client.send(byteBuffer);
        }
        else
        {
            logger.error("user: " + uid + " not online, cann't receive message!");
        }
    }

    /**
     * 向所有的用户发送一个协议包
     * @param byteBuffer 要发送的协议包
     */
    public static void notifyAll(ByteBuffer byteBuffer)
    {
        if(_clientMap != null && _clientMap.size() > 0)
        {
            for(Map.Entry<Integer, RemoteClientSocket> entry : _clientMap.entrySet())
            {
                entry.getValue().send(byteBuffer);
            }
        }
    }

    /**
     * 向除自己以外的所有用户发送一个协议包
     * @param self 指定当前用户的套接字客户端对象
     * @param byteBuffer 要发送的协议包
     */
    public static void notifyALLWithoutSelf(RemoteClientSocket self, ByteBuffer byteBuffer)
    {
        if(_clientMap != null && _clientMap.size() > 0)
        {
            for(Map.Entry<Integer, RemoteClientSocket> entry : _clientMap.entrySet())
            {
                if(entry.getValue().uid() == self.uid())
                {
                    continue;
                }
                entry.getValue().send(byteBuffer);
            }
        }
    }
}
